<template>
  <div style="display: flex; flex-direction: column; align-items: center; width: 100%">
    <img src="https://alicdn.antdv.com/v2/assets/logo.1ef800a8.svg" style="margin-top: 20px" />
    <h1 style="margin-top: 20px">用户管理中心</h1>
  </div>

  <a-card class="login-card">
    <a-tabs :centered="true">
      <a-tab-pane key="account" tab="账户密码登录">
        <a-form @submit="handleSubmit" ref="formRef" :rules="rules" :model="account">
          <a-form-item name="userAccount">
            <a-input v-model:value="account.userAccount" placeholder="Username" autocomplete="off">
              <template #prefix>
                <UserOutlined />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item name="userPassword">
            <a-input
              v-model:value="account.userPassword"
              type="password"
              placeholder="Password"
              autocomplete="off"
            >
              <template #prefix>
                <LockOutlined />
              </template>
            </a-input>
          </a-form-item>
          <!-- <a-form-item name="code">
              <div style="display: flex; align-items: center">
                <a-input
                  v-model:value="account.code"
                  type="number"
                  placeholder="code"
                  autocomplete="off"
                >
                  <template #prefix>
                    <VerifiedOutlined />
                  </template>
                </a-input>
                <img
                  :src="captchaImage"
                  alt="Captcha"
                  v-if="captchaImage"
                  style="width: 70px; height: 30px; margin-left: 10px"
                  @click="fetchCaptcha()"
                />
              </div>
            </a-form-item> -->
          <a-form-item>
            <a-button type="primary" htmlType="submit" block>
              {{ `${loading ? '登录中...' : '登录'}` }}
            </a-button>
          </a-form-item>
          <a-form-item>
            <a @click="goToRegister">注册</a>
            <a style="float: right" @click="forgotPassword">忘记密码?</a>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <!-- <a-tab-pane key="phone" tab="Phone Login">
          <a-form @submit="handleSubmit">
            <a-form-item>
              <a-input v-model="phone.phoneNumber" placeholder="Phone Number">
                <template #prefix>
                  <PhoneOutlined />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-row :gutter="8">
                <a-col span="16">
                  <a-input v-model="phone.verificationCode" placeholder="Verification Code" />
                </a-col>
                <a-col span="8">
                  <a-button @click="getVerificationCode">Get Code</a-button>
                </a-col>
              </a-row>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" htmlType="submit" block>
                {{ `${loading === false ? '登录' : '登录中...'}` }}
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane> -->
    </a-tabs>
  </a-card>
</template>
  
  <script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import Icon, {
  HomeOutlined,
  UserOutlined,
  LockOutlined,
  PhoneOutlined,
  VerifiedOutlined,
} from '@ant-design/icons-vue';

//公共区域

//公共区域

//获取验证码
//   import { getCaptcha } from '@/api/user-api/userApi';
//   let captchaImage = ref('');
//   const fetchCaptcha = async () => {
//     try {
//       const response = await getCaptcha();
//       account.value.uuid = response.uuid;
//       captchaImage.value = 'data:image/png;base64,' + response.img;
//     } catch (error) {
//       message.error('Failed to fetch captcha');
//     }
//   };
//   onMounted(()=>{fetchCaptcha()});
//获取验证码

//登录
import type { LoginData, UserInfo } from '@/type/type';
const account = ref<LoginData>({
  userAccount: 'adminlxw',
  userPassword: '123123123123',
});
import { login } from '@/api/user-api/userApi';
let loading = ref(false);
const handleSubmit = async (e: any) => {
  loading.value = true;
  e.preventDefault();
  try {
    console.log(account.value);
    //   let tmp = {
    //     userAccount: account.value.userAccount,
    //     userPassword: account.value.userPassword,
    //   };
    const formData = new FormData();
    formData.append('userAccount', account.value.userAccount);
    formData.append('userPassword', account.value.userPassword);
    const response = await login(formData);
    console.log(response);
    if (response !== null && response.userAccount) {
      message.success('身份验证成功');
      loading.value = false;
      localStorage.setItem('userAccount', response.userAccount);
      toIndex();
    }
    if (response === null) {
      message.error('请检查账号或者密码');
    }
  } catch (error) {
    message.error('Failed to fetch captcha');
  }

  loading.value = false;
};
const toIndex = () => {
  router.replace({ path: '/' });
};
//登录

//表单验证
// let formRef = ref<FormInstance>();
const validateUser = async (_rule: Rule, value: string) => {
  if (value.length < 3) {
    console.log(account.value.userAccount);
    return Promise.reject('must more than 3');
  } else {
    return Promise.resolve();
  }
};
const validatePass = async (_rule: Rule, value: string) => {
  if (value.length < 5) {
    return Promise.reject('must more than 5');
  } else {
    return Promise.resolve();
  }
};
// const validateCode = async (_rule: Rule, value: string) => {
//   if (value.length < 1) {
//     return Promise.reject('please input code!');
//   } else {
//     return Promise.resolve();
//   }
// };
const rules: Record<string, Rule[]> = {
  userAccount: [{ required: true, validator: validateUser, trigger: 'change' }],
  userPassword: [{ required: true, validator: validatePass, trigger: 'change' }],
};
//表单验证

//手机登录
//   const phone = ref({
//     phoneNumber: '',
//     verificationCode: '',
//   });

//   const getVerificationCode = () => {
//     message.success('Verification code sent to your phone');
//   };
//手机登录

//其它
const router = useRouter();
const goToRegister = () => {
  router.push('/register');
};
const forgotPassword = () => {
  router.push('/forgot-password');
};
//其它
</script>
  
  <style scoped>
.login-card {
  max-width: 400px;
  margin: 20px auto;
  padding: 20px;
}
</style>
  